﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using NHibernate;
using NHibernate.Cfg;

namespace YoProgramo.Infrastructure.Data.NHIbernate
{
    public class NHWrapper {
        public static Configuration _config;
        public static ISessionFactory _sFactory;
        public static ISession _session;
        private static readonly string _sessionKey = "NHSession";
        private static readonly string _factoryKey = "NHFactory";



        #region Constructors
        public NHWrapper(string configurePath) {
            _config = new Configuration();
            _config.Configure(configurePath);
        }

        public NHWrapper(Configuration c, string configurePath) {
            _config = c;
            _config.Configure(configurePath);
        } 
        #endregion

        public static ISessionFactory BuildSessionFactory()
        {
            if (HttpContext.Current.Items[_factoryKey] == null)
            {
                _sFactory = _config.BuildSessionFactory();
                HttpContext.Current.Items[_factoryKey] = _sFactory;
                
            }
            return HttpContext.Current.Items[_factoryKey] as ISessionFactory;

        }
        public static ISession CreateSession()
        {
            if (HttpContext.Current.Items[_sessionKey] == null)
            {
                _session = _sFactory != null 
                               ? _sFactory.OpenSession() : BuildSessionFactory().OpenSession();

                HttpContext.Current.Items[_sessionKey] = _session;
            }

            return HttpContext.Current.Items[_sessionKey] as ISession;            
        }

        public static ISession GetCurrentSession()
        {
            if (HttpContext.Current.Items[_sessionKey] == null)
                CreateSession();

            return HttpContext.Current.Items[_sessionKey] as ISession;            
        }

    }
}